package com.ynny.usermanager.dao;

import com.ynny.usermanager.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public User selectUserById(Integer id) {

        String sql = "select * from user where id = ?";
        User user = jdbcTemplate.queryForObject(sql,
                new BeanPropertyRowMapper<>(User.class),
                id);

        return user;
    }

    @Override
    public List<User> selectAllUsers() {

        String sql = "select * from user";
        List<User> users
                = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<>(User.class));
        return users;
    }

    @Override
    public int addUser(User user) {

        String sql = "insert into user (username,password,age,sex,identity,hobby) values(?,?,?,?,?,?)";
        int i = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getAge(),
                user.getSex(),
                user.getIdentity(),
                user.getHobby());


        return i;
    }

    @Override
    public int updateUser(User user) {
        String sql = "update user set username = ? , password = ?,age = ? where id = ?";
        int i = jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getAge(),
                user.getId());
        return i;
    }

    @Override
    public int deleteUser(Integer id) {

        String sql = "delete from user where id = ?";
        int i = jdbcTemplate.update(sql, id);

        return i;
    }

    @Override
    public User selectUserByUserName(String username) {

        String sql = "select * from user where username = ?";
        List<User> list = jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<>(User.class),
                username);

        if (list.size() == 0){
            return null;
        }

        return list.get(0);
    }
}
